<template>
  <div class="max-w-[800px] mx-auto pb-[80px] bg-gray-100 min-h-screen">
    <!-- 1. 顶部返回栏 (保持不变) -->
    <div class="sticky top-0 z-10 flex items-center py-3.75 px-5 bg-white shadow-sm">
      <button @click="goToHome" class="flex items-center gap-1.25 bg-transparent border-none p-2 rounded-full transition-all hover:bg-gray-100 active:scale-95">
        <!-- 返回图标 -->
        <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
          <path d="M19 12H5M12 19l-7-7 7-7"/>
        </svg>
        <span>返回</span>
      </button>
      <h2 class="flex-1 text-center m-0 text-lg font-semibold text-gray-800 truncate px-2.5">{{ restaurant.name }}</h2>
    </div>

    <!-- 2. 商家信息区 (改为上下布局) -->
    <div class="bg-white p-3.75 mt-2.5 rounded-lg shadow-sm mb-3.75">
      <!-- 商家图片 (144x144px) -->
      <div class="w-36 h-36 mx-auto mb-3.75 overflow-hidden rounded">
        <img
            :src="restaurant.image"
            :alt="restaurant.name"
            class="w-full h-full object-cover"
        />
      </div>

      <!-- 商家文字信息 -->
      <div class="text-center">
        <h1 class="m-0 mb-2 text-xl text-gray-800">{{ restaurant.name }}</h1>
        <div class="flex justify-center items-center mb-1.25">
          <span class="text-yellow-500 text-base">★★★★☆</span>
          <span class="text-sm text-gray-600 ml-1.25">{{ restaurant.rating }}</span>
        </div>
        <p class="m-0 text-sm text-gray-600">月售 {{ restaurant.sales }} 单</p>
        <p class="m-0 text-sm text-gray-600">人均: ¥{{ restaurant.avgPrice }}</p>
        <p class="m-0 text-sm text-gray-600">{{ restaurant.status }} | {{ restaurant.deliveryType }}</p>
      </div>
    </div>

    <!-- 3. 分类筛选模块 (保持不变) -->
    <div class="flex flex-wrap gap-2 mb-3.75 py-2.5">
      <button
          v-for="(category, index) in categories"
          :key="index"
          class="px-3 py-1.5 border rounded-full text-sm transition-all"
          :class="selectedCategory === category
          ? 'bg-yellow-500 text-white border-yellow-500'
          : 'bg-white text-gray-600 border-gray-300'"
          @click="selectedCategory = category"
      >
        {{ category }}
      </button>
    </div>

    <!-- 4. 菜品卡片 (新布局) -->
    <div class="flex flex-col gap-3">
      <div
          v-for="(dish, index) in filteredDishes"
          :key="index"
          class="flex bg-white p-3 rounded-lg shadow-sm"
      >
        <!-- 菜品图片 (左侧) -->
        <div class="w-24 h-24 flex-shrink-0 overflow-hidden rounded mr-3">
          <img
              :src="dish.image"
              :alt="dish.name"
              class="w-full h-full object-cover"
          />
        </div>

        <!-- 文字信息 (中部) -->
        <div class="flex-1">
          <h2 class="m-0 mb-1 text-base text-gray-800">{{ dish.name }}</h2>
          <p class="m-0 text-xs text-gray-500 mb-1">{{ dish.category }}</p>
          <p class="m-0 text-base font-bold text-yellow-500">¥{{ dish.price }}</p>
        </div>

        <!-- 加减按钮 (右侧) -->
        <div class="flex flex-col items-center justify-center ml-auto pl-2">
          <div class="flex items-center gap-2">
            <button
                @click="decrement(dish)"
                :disabled="getDishCount(dish) === 0"
                class="w-7 h-7 rounded-full border border-yellow-500 bg-white text-yellow-500 flex items-center justify-center disabled:opacity-50 disabled:cursor-not-allowed"
            >-</button>
            <span class="min-w-[20px] text-center">{{ getDishCount(dish) }}</span>
            <button
                @click="increment(dish)"
                class="w-7 h-7 rounded-full border border-yellow-500 bg-white text-yellow-500 flex items-center justify-center"
            >+</button>
          </div>
        </div>
      </div>
    </div>

    <!-- 5. 底部结算栏 (保持不变) -->
    <div class="fixed bottom-0 left-0 right-0 h-[60px] bg-white flex justify-between items-center p-3.75 shadow-[0_-2px_5px_rgba(0,0,0,0.1)] z-[100] max-w-[800px] mx-auto">
      <div class="text-lg font-bold text-yellow-500">总计: ¥{{ totalAmount }}</div>
      <button
          class="bg-yellow-500 text-white border-none rounded-full px-5 py-2 text-sm font-bold disabled:bg-gray-300 disabled:cursor-not-allowed"
          @click="checkout"
          :disabled="totalAmount === '0.00'"
      >结算({{ totalItems }}件)</button>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import restaurantData from '@/assets/restaurantData.json'

export default {
  setup() {
    const route = useRoute()
    const router = useRouter()

    const goToHome = () => {
      router.push({ name: 'home' })
    }

    // 响应式数据
    const restaurant = ref({ dishes: [] })
    const selectedCategory = ref('全部')
    const categories = ref(['全部'])
    const selectedDishes = ref({})

    // 计算属性
    const filteredDishes = computed(() => {
      if (selectedCategory.value === '全部') {
        return restaurant.value.dishes
      }
      return restaurant.value.dishes.filter(dish => dish.category === selectedCategory.value)
    })

    const totalAmount = computed(() => {
      return restaurant.value.dishes.reduce((total, dish) => {
        const count = selectedDishes.value[dish.name] || 0
        return total + (parseFloat(dish.price) * count)
      }, 0).toFixed(2)
    })

    const totalItems = computed(() => {
      return Object.values(selectedDishes.value).reduce((total, count) => total + count, 0)
    })

    // 方法
    const loadRestaurantData = () => {
      const restaurantId = parseInt(route.params.id)
      const found = restaurantData.restaurants.find(r => r.id === restaurantId)

      if (found) {
        const total = found.dishes?.reduce((sum, dish) => sum + parseFloat(dish.price), 0) || 0
        const count = found.dishes?.length || 1

        const processImages = (restaurant) => {
          return {
            ...restaurant,
            image: restaurant.image ? require(`@/assets${restaurant.image}`) : require('@/assets/default-restaurant.jpg'),
            dishes: restaurant.dishes?.map(dish => ({
              ...dish,
              image: dish.image ? require(`@/assets${dish.image}`) : require('@/assets/default-restaurant.jpg')
            })) || []
          }
        }

        restaurant.value = processImages({
          ...found,
          avgPrice: (total / count).toFixed(2)
        })

        const allCategories = ['全部']
        restaurant.value.dishes?.forEach(dish => {
          if (!allCategories.includes(dish.category)) {
            allCategories.push(dish.category)
          }
          if (!selectedDishes.value.hasOwnProperty(dish.name)) {
            selectedDishes.value[dish.name] = 0
          }
        })
        categories.value = allCategories
      }
    }

    const getDishCount = (dish) => {
      return selectedDishes.value[dish.name] || 0
    }

    const increment = (dish) => {
      selectedDishes.value[dish.name] = (selectedDishes.value[dish.name] || 0) + 1
    }

    const decrement = (dish) => {
      if (selectedDishes.value[dish.name] > 0) {
        selectedDishes.value[dish.name] -= 1
      }
    }

    const checkout = () => {
      const orderItems = restaurant.value.dishes
          .filter(dish => selectedDishes.value[dish.name] > 0)
          .map(dish => ({
            name: dish.name,
            price: dish.price,
            count: selectedDishes.value[dish.name],
            image: dish.image
          }))

      if (orderItems.length === 0) {
        alert('请至少选择一件商品')
        return
      }

      router.push({
        name: 'checkout',
        query: {
          orderItems: JSON.stringify(orderItems),
          totalAmount: totalAmount.value,
          shopName: restaurant.value.name,
          shopImage: restaurant.value.image
        }
      })
    }

    // 生命周期钩子
    onMounted(() => {
      loadRestaurantData()
    })

    return {
      restaurant,
      selectedCategory,
      categories,
      filteredDishes,
      totalAmount,
      totalItems,
      getDishCount,
      increment,
      decrement,
      checkout,
      goToHome
    }
  }
}
</script>